import { useMutation, useQueryClient } from '@tanstack/react-query';
import { Form, Input, message, Modal } from 'antd';
import { saveAs } from 'file-saver';
import React from 'react';

import api from '@/apis/api';
import { Logger } from '@/components/useLogger';

interface BackupKeyModalProps {
  title: string;
  visible: boolean;
  setVisible: (visible: boolean) => void;
}

const BackupKeyModal: React.FC<BackupKeyModalProps> = ({
  title = '备份用户密钥',
  visible,
  setVisible,
}) => {
  const [form] = Form.useForm();

  const queryClient = useQueryClient();
  const [fileName, setFileName] = React.useState<string>();

  const BackupKeyLog = useMutation({
    mutationFn: (params: any) => api.BackupKeyLog(params),
    onSuccess: async (res: any) => {
      // 检查响应的内容类型
      const contentType = res.type;

      // 如果返回的是 Blob 数据
      if (contentType === 'application/octet-stream') {
        const blob = new Blob([res], { type: 'application/octet-stream' });
        saveAs(blob, fileName); // 下载文件
        message.success('备份成功');
      } else {
        // 否则，处理 JSON 错误响应
        const responseData = JSON.parse(await res.text());
        if (responseData.success === false) {
          Logger(responseData.message);
          message.error(`备份失败，${responseData.message}`);
        } else {
          message.success('备份成功');
        }
      }
    },
    onError: (error: any) => {
      Logger(error);
      message.error('备份失败');
    },
    onSettled: () => queryClient.invalidateQueries({ queryKey: ['getKeyManageData'] }),
    mutationKey: ['getKeyManageData'],
  });

  const handleBackupeOk = async () => {
    await form.validateFields();
    const values = form.getFieldsValue();
    const fName = values.backupFileName + '.hust';
    if (title === '备份用户密钥') {
      BackupKeyLog.mutate({
        pincode: values.backupKeyCode,
        filename: fName,
      });
    }
    setFileName(fName);
    form.resetFields();
    setVisible(false);
  };
  const handleBackupCancel = () => {
    form.resetFields();
    setVisible(false);
    setFileName('');
  };

  type FieldType = {
    backupKeyCode?: string;
    backupFileName?: string;
    rbackupKeyCode?: string;
  };

  return (
    <>
      <Modal
        title={title}
        open={visible}
        onOk={handleBackupeOk}
        onCancel={handleBackupCancel}
        cancelText="取消"
        okText="导出"
        destroyOnClose
        // okButtonProps={{ disabled: localINFO.getRoleId() !== 1 }}
      >
        <Form
          form={form}
          preserve={false}
          name="basic"
          labelCol={{ span: 7 }}
          wrapperCol={{ span: 16 }}
          style={{ maxWidth: 600, marginTop: 24 }}
          autoComplete="off"
        >
          <Form.Item<FieldType>
            label="备份密钥口令"
            name="backupKeyCode"
            rules={[{ required: true, message: '请输入备份密钥口令！' }]}
          >
            <Input.Password
              autoComplete="new-password"
              placeholder="请输入备份密钥口令"
            />
          </Form.Item>

          <Form.Item<FieldType>
            label="确认备份密钥口令"
            name="rbackupKeyCode"
            rules={[
              ({ getFieldValue }) => ({
                validator(rule, value) {
                  if (!value || getFieldValue('backupKeyCode') === value) {
                    return Promise.resolve(rule);
                  }
                  return Promise.reject('两次备份密钥口令不同！');
                },
              }),
              { required: true, message: '请再输入备份密钥口令!' },
            ]}
          >
            <Input.Password
              autoComplete="new-password"
              placeholder="请确认备份密钥口令"
            />
          </Form.Item>

          <Form.Item<FieldType>
            label="保存的备份文件名"
            name="backupFileName"
            rules={[{ required: true, message: '请输入保存的备份文件名！' }]}
          >
            <Input placeholder="请输入保存的备份文件名" />
          </Form.Item>
        </Form>
      </Modal>
    </>
  );
};

export default BackupKeyModal;
